<?php

namespace app\admin\model\cms;

use addons\cms\library\FulltextSearch;
use addons\cms\library\Service;
use app\common\model\User;
use think\Model;
use traits\model\SoftDelete;
use think\Db;

class Collect extends Model
{
//    use SoftDelete;

    // 表名
    protected $name = 'cms_collect_article';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名


    protected static $config = [];
    protected static function init()
    {

        self::$config = $config = get_addon_config('cms');
        self::beforeInsert(function ($row) {

            if (!isset($row['admin_id']) || !$row['admin_id']) {
                $admin_id = session('admin.id');
                $row['admin_id'] = $admin_id ? $admin_id : 0;
            }
        });
        self::afterInsert(function ($row) {

            $pk = $row->getPk();
            $channel = Channel::get($row['channel_id']);
            $row->getQuery()->where($pk, $row[$pk])->update(['model_id' => $channel ? $channel['model_id'] : 0]);
            Channel::where('id', $row['channel_id'])->setInc('items');
        });
        self::beforeWrite(function ($row) {

            $changedData = $row->getChangedData();
            if (isset($changedData['flag'])) {
                $row['weigh'] = is_array($changedData['flag']) && in_array('top', $changedData['flag'])
                    ? ($row['weigh'] == 0 ? 9999 : $row['weigh'])
                    : ($row['weigh'] == 9999 ? 0 : $row['weigh']);
            }

            if (isset($row['content'])) {
                $row['content'] = Service::autolinks($row['content']);
            }
            //在更新之前对数组进行处理
            foreach ($row->getData() as $k => $value) {
                if (is_array($value) && is_array(reset($value))) {
                    $value = json_encode(self::getArrayData($value), JSON_UNESCAPED_UNICODE);
                } else {
                    $value = is_array($value) ? implode(',', $value) : $value;
                }
                $row->$k = $value;
            }
        });
        self::afterWrite(function ($row) use ($config) {

            if (isset($row['channel_id'])) {
                //在更新成功后刷新副表、TAGS表数据、栏目表
                $channel = Channel::get($row->channel_id);
                if ($channel) {
                    $model = Modelx::get($channel['model_id']);
                    if ($model && isset($row['content'])) {
                        $values = array_intersect_key($row->getData(), array_flip($model->fields));
                        $values['id'] = $row['id'];
                        $values['uid'] = $row['school_id'];
                        $values['content'] = $row['content'];
                        db($model['table'])->insert($values, true);
                        if (strtolower(request()->action())=='edit'&& isset($values['province'])){
                            DB::name('cms_archives_province')->where(['archives_id'=>$row['id']])->delete();
                        }

                        if (strtolower(request()->action())=='edit'&& isset($row['province'])){
                            DB::name('cms_archives_special')->where(['archives_id'=>$row['id']])->delete();
                        }

                        if ($row['special_ids']){
                            $special_ids=explode(",",$row['special_ids']);
                            for ($i=0;$i<count($special_ids);$i++){
                                if ($special_ids[$i]){
                                    DB::name('cms_archives_special')->insert(['special_id'=>$special_ids[$i],'archives_id'=>$row['id']]);
                                }
                            }
                        }
                        if (empty($values['province'])){
                            DB::name('cms_archives_province')->insert(['province_id'=>1,'archives_id'=>$row['id']]);
                        }else{
                            $province=explode(",",$values['province']); //插入省份表
                            for ($i=0;$i<count($province);$i++){
                                if ($province[$i]){
                                    DB::name('cms_archives_province')->insert(['province_id'=>$province[$i],'archives_id'=>$row['id']]);
                                }
                            }
                        }
                    }
                }
            }
            if (isset($row['tags'])) {
                \addons\cms\model\Tag::refresh($row['tags'], $row['id']);
            }
            $changedData = $row->getChangedData();
            if (isset($changedData['status']) && $changedData['status'] == 'normal') {
                //增加积分
                User::score($config['score']['postarchives'], $row['user_id'], '发布文章');
                //推送到熊掌号和百度站长
                if ($config['baidupush']) {
                    $urls = [$row->fullurl];
                    \think\Hook::listen("baidupush", $urls);
                }
            }
            if ($config['searchtype'] == 'xunsearch') {
                //更新全文搜索
                FulltextSearch::update($row->id);
            }
        });
        self::afterDelete(function ($row) use ($config) {
            $data = Archives::withTrashed()->find($row['id']);
            if ($data) {
                if ($row['status'] == 'normal') {
                    User::score(-$config['score']['postarchives'], $row['user_id'], '删除文章');
                }
                if ($config['searchtype'] == 'xunsearch') {
                    FulltextSearch::del($row);
                }
            } else {
                //删除相关TAG
                \addons\cms\model\Tag::refresh('', $row['id']);
            }
            //删除评论
            Comment::deleteByType('archives', $row['id'], !$data);
        });
    }

}